import React, { Component, ComponentClass } from 'react';
import {connect} from 'react-redux'
import Taro from '@tarojs/taro';
import {View, Text, Block} from '@tarojs/components'
import {AtSearchBar, AtIndexes, AtIcon} from 'taro-ui'
import {HotCity, CityLocation, AllCity} from '../../utils/server.interface'
import {location} from '../../utils/location.service'
import {setCity, autoLocation} from '../../actions/location'
import {http} from '../../utils/http'
import {HOT_CITY, SEARCH_CITY, ALL_CITY} from '../../constants/api'
import {h5Wx} from "../../utils/h5.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import {vcmonitor} from "../../utils/tools";
import './select-city.scss'

interface StateType {
  hotCity: HotCity[]
  allCity: AllCity[]
  searchKey: string
  searchCity: HotCity[]
}

type PageStateProps = {
  location: CityLocation
}

type PageDispatchProps = {
  setCity: (city: CityLocation) => void
  autoLocation: (city: CityLocation) => void
}

type PageOwnProps = {}

type PageState = {}

type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface SelectCity {
  props: IProps
}

@connect(({location}) => ({
  location
}), (dispatch) => ({
  setCity(city) {
    dispatch(setCity(city))
  },
  autoLocation(city) {
    dispatch(autoLocation(city))
  }
}))

class SelectCity extends Component {
  state: StateType = {
    hotCity: [],
    allCity: [],
    searchKey: '',
    searchCity: []
  }

  async componentDidShow() {
    vcmonitor(this);
  }

  async UNSAFE_componentWillMount() {
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    this.assignmentMethod = Taro.getCurrentInstance().router.params.assignmentMethod || ''
    Taro.showLoading({title: '加载城市中...'})
    let hotCity: any = []
    if (this.assignmentMethod && this.assignmentMethod !== 'prePage') {
      hotCity = await http.get<HotCity[]>(HOT_CITY, {})
    }
    const allCity = await http.get<AllCity[]>(ALL_CITY, {})
    if (hotCity) {
      this.setState({hotCity, allCity})
    }
    Taro.hideLoading()
  }

  async search() {
    const searchCity = await http.get(SEARCH_CITY, {keywords: this.state.searchKey})
    if (searchCity) {
      this.setState({searchCity})
    }
  }

  inputChange(value) {
    this.setState({searchKey: value})
  }

  hotCityHandle(item, e) {
    if (this.assignmentMethod && this.assignmentMethod === 'prePage') {
      this.setAreaName(item.area_name)
    } else {
      location.ignore = true
      e.stopPropagation()
      this.props.setCity(item)
      this.naviBack()
    }
  }

  setAreaName(area_name){
    const pages = Taro.getCurrentPages()
    const prevPage = pages[pages.length - 2]
    if (prevPage) {
      prevPage.data.currentPageCity = area_name
      prevPage.data.choiceCity = area_name
      this.naviBack()
    }
  }

  indexes(value) {
    const {area_name, region_id} = value
    if (this.assignmentMethod && this.assignmentMethod === 'prePage') {
      this.setAreaName(area_name)
    } else {
      this.props.setCity({area_name, region_id})
      this.naviBack()
    }
  }

  relocation(e) {
    e.stopPropagation()
    try {
      location.getLocation().then(async (res: any) => {
        if (res == null) {
          console.log('不是微信浏览器');
        } else {
          if (process.env.TARO_ENV === 'h5') {
            const city = await location.getLocationNewH5City(res.longitude, res.latitude, 'wgs84')
            if (city) {
              this.props.autoLocation(city)
            }
          } else {
            const city = await location.getLocationCity(res.longitude, res.latitude)
            if (city) {
              this.props.autoLocation(city)
            }
          }
        }
      })
    } catch (e) {
      Taro.showModal({
        title: '提示',
        content: '您需要开启手机的GPS定位, 才能为您匹配精准的自提点信息'
      })
    }
  }

  naviBack() {
    Taro.navigateBack({
      delta: 1
    })
  }

  clearSearch() {
    this.setState({searchKey: '', searchCity: []})
  }

  assignmentMethod: any = ''

  render() {
    const {hotCity, allCity, searchCity, searchKey} = this.state
    return (
      <View className='select-all-city'>
        <GzhAuth />
        <AtIndexes animation onClick={this.indexes.bind(this)} list={allCity}>
          <View className='root'>
            <AtSearchBar value={searchKey} onClear={this.clearSearch.bind(this)} onChange={this.inputChange.bind(this)}
              onActionClick={this.search.bind(this)} placeholder='城市名称，如：北京'
            />
            {searchCity.length === 0 && <Block>
              <View className='now-city'>
                <View className='title'>当前定位城市：</View>
                <View className='content'>
                  <View className='location' onClick={()=>{
                    if (this.assignmentMethod === 'prePage') {
                      return false
                    }
                    this.naviBack()
                  }}
                  ><AtIcon value='map-pin'
                    size='16'
                    customStyle='line-height: inherit;vertical-align: baseline;'
                  /><Text
                    className='city-name'
                  >{this.props.location.area_name}</Text>
                  </View>
                  {this.assignmentMethod !== 'prePage' && <View className='relocation' onClick={this.relocation.bind(this)}>重新定位</View>}
                </View>
              </View>
              {hotCity.length > 0 && <View className='hot-city'>
                <View className='title'>热门城市</View>
                <View className='content'>
                  {hotCity.map((item, index) => <View className='tag-box' key={index}
                    onClick={this.hotCityHandle.bind(this, item)}
                  ><View
                    className='tag'
                  >{item.area_name}</View></View>)}
                </View>
              </View>}
            </Block>
            }
            {searchCity.length > 0 && searchCity.map((item, index) => <View key={index} className='item' style='font-size: 17px'
              onClick={this.hotCityHandle.bind(this, item)}
            >{item.area_name}</View>)}
          </View>
        </AtIndexes>
      </View>
    )
  }
}

export default SelectCity as ComponentClass<PageOwnProps, PageState>
